package com.example.PDFdemo.json;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class PDFUtil {

    public static void fillPdf(String oldFilePath, String newFilePath, List<FillInfo> fillInfoList) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(oldFilePath);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));
        for (FillInfo fillInfo : fillInfoList) {
            PdfContentByte over = stamper.getOverContent(fillInfo.getPageNo());
            //创建矩形
            Rectangle rect = new Rectangle(reader.getPageSizeWithRotation(fillInfo.getPageNo()));
            float x = rect.getRight();
            float y = rect.getTop();
            //获取图片
            Image image = Image.getInstance(fillInfo.getContent());
            //添加图片
            over.saveState();
            PdfGState state = new PdfGState();
            // 设置填充透明度
            state.setFillOpacity(1.0f);
            over.setGState(state);
            // pdf 图层图片渲染
            over.addImage(image, x * fillInfo.getSw(), 0f, 0f, y * fillInfo.getSh(), fillInfo.getSx() * x, fillInfo.getSy() * y);
            over.restoreState();
        }
        stamper.close();
        reader.close();
    }
}
